import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';

class TaskList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TaskList'),
        elevation: 0.0,
      ),
      body: TaskListHome(),
    );
  }
}

class TaskListHome extends StatefulWidget {
  @override
  _TaskListHomeState createState() => _TaskListHomeState();
}

class _TaskListHomeState extends State<TaskListHome> {
  @override
  void initState() {
    super.initState();
    // fetchPosts()
    //   .then((value) => print(value));

    // final post = {
    //   'title': 'hello',
    //   'description': 'nice to meet you.',
    // };

    // print(post['title']);
    // print(post['description']);

    // final postJson = json.encode(post);
    // print(postJson);

    // final postJsonConverted = json.decode(postJson);
    // print(postJsonConverted['title']);
    // print(postJsonConverted['description']);
    // print(postJsonConverted is Map);

    // final postModel = Post.fromJson(postJsonConverted);
    // print('title: ${postModel.title}, description: ${postModel.description}');

    // print('${json.encode(postModel)}');
  }

  Future fetchPosts() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    // 获得密码
    final codeResponse = await http.get(
      'https://me.yuanqiao.pw/api/me/getInventoryList.php?limit=60&offset=0',
      headers: {HttpHeaders.authorizationHeader: prefs.get('user_token')},
    );
    if (codeResponse.statusCode == 200) {
      final codeResponseBody = json.decode(codeResponse.body);
      if(codeResponseBody['state'] != '1') {
        Navigator.of(context).pushNamedAndRemoveUntil('/login', (route) => route == null,);
      }else{
        List<Post> posts = codeResponseBody['data']
          .map<Post>((item) => Post.fromJson(item))
          .toList();
        print(posts);
        return posts;
      }

    }
  }
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: fetchPosts(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        print('data: ${snapshot.data}');
        print('connectionState: ${snapshot.connectionState}');
        if (snapshot.connectionState == ConnectionState.waiting) {
          return Center(
            child: Text('loading...'),
          );
        }
        return ListView(
          children: snapshot.data.map<Widget>((item) {
            return ListTile(
              title: Text(item.content),
              subtitle: Text(item.date)
            );
          }).toList(),
        );
      },
    );
  }
}

class Post {
  final String id;
  final String classify;
  final String content;
  final String date;
  final String create_date;
  final String status;
  final String type;
  final String userid;

  Post(
    this.id,
    this.classify,
    this.content,
    this.date,
    this.create_date,
    this.status,
    this.type,
    this.userid
  );

  Post.fromJson(Map json)
    : id = json['id'],
      classify = json['classify'],
      content = json['content'],
      date = json['date'],
      create_date = json['create_date'],
      status = json['status'],
      type = json['type'],
      userid = json['userid'];

  Map toJson() => {
    'content': content,
    'date': date,
    'status': status,
    'type': type
  };
}
